package com.wyp.design.pattern.creational.singleton.reflectattack;


import java.lang.reflect.Constructor;

/**
 * 饿汉式中防止反射攻击
 *
 * @author: yipeng.wang01@hand-china.com-25490
 * @TIME: 2020/1/2/17:00
 **/
public class HungrySingleton {
    private final static HungrySingleton hungrySingleton;
    //当然初始化操作也可以放在静态代码块中

    static {
        hungrySingleton = new HungrySingleton();
    }

    private HungrySingleton() {
        if(hungrySingleton!=null){
            throw  new RuntimeException("单例构造器禁止反射创建！");
        }
    }

    public static HungrySingleton getInstance() {
        return hungrySingleton;
    }

    private Object readResolve() {
        return hungrySingleton;
    }

    public static void main(String[] args) throws Exception {
        //使用反射进行创建对象
        Class<HungrySingleton> hungrySingletonClass = HungrySingleton.class;
        //获取私有构造器
        Constructor<HungrySingleton> constructor = hungrySingletonClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        HungrySingleton newInstance = constructor.newInstance();
        HungrySingleton instance = HungrySingleton.getInstance();
        System.out.println(newInstance);
        System.out.println(instance);
        System.out.println(newInstance == instance);

    }
}
